//
//  LauWelcomeView.swift
//  SwiftProject
//
//  Created by Lausen on 2017/8/17.
//  Copyright © 2017年 id. All rights reserved.
//

import UIKit
import SDWebImage

/// 欢迎界面的自定义
class LauWelcomeView: UIView {

    /// 欢迎界面头像视图
    @IBOutlet weak var iconImageView: UIImageView!
    /// 欢迎界面label视图
    @IBOutlet weak var label: UILabel!
    /// 欢迎界面头像的底部约束
    @IBOutlet weak var bottomCons: NSLayoutConstraint!
    
    //MARK: -- 返回欢迎界面
    /// 返回欢迎界面实例的类方法
    ///
    /// - Returns: 返回欢迎界面的实例
    class func welcomeView() -> LauWelcomeView{
        
        //1:从nib加载视图
        let nib = UINib.init(nibName: "LauWelcomeView", bundle: Bundle.main)
        
        //2:实例化nib
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! LauWelcomeView
        
        //3:在这儿设置xib的大小,因为xib的大小是默认的600*600
        v.frame = UIScreen.main.bounds
        
        return v
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        
        //加载头像
        guard let urlString = LauNetworkManager.shared.account.avatar_large,
            let url = URL(string: urlString) else{
                
                return
        }
        
        iconImageView.sd_setImage(with: url, placeholderImage: UIImage(named: "avatar_default_big"))
        
        //2:设置圆角
        /*
         利用了xib里面设置keypath来设置的圆角
         */
    }
    
    //MARK: -- 当视图被加载到window上面的时候(即:显示出来的时候),就会调用的方法
    override func didMoveToWindow() {
        super.didMoveToWindow()
        // 当视图加载到window上面的时候,frame有可能还设置好,这个时候,调用 self.layoutIfNeeded() 可能都会跟着一起做动画效果
        //需要在次调用self.layoutIfNeeded()
        layoutIfNeeded()
        
        bottomCons.constant = bounds.height - 200
        
        UIView.animate(withDuration: 1.0,
                       delay: 0.0,
                       usingSpringWithDamping: 0.7,
                       initialSpringVelocity: 0.0,
                       options: [],
                       animations: { 
                        
                        self.layoutIfNeeded()
        }) { (_) in
            
            //头像的动画结束之后,设置"欢迎归来"的alpha为1
            UIView.animate(withDuration: 1.0, animations: { 
                
                self.label.alpha = 1.0
                
            }, completion: { (_) in
                
                self.removeFromSuperview()
                
            })
        }
    }
    
}
